
<template>
  <BasicLayout>
    <template #wrapper>
      <el-card class="box-card" style="padding: 36px">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="资料名称" prop="name">
            <el-input v-model="form.name" style="width: 40%" placeholder="请输入课程名称" />
          </el-form-item>
          <el-form-item label="资料类型" prop="type">
            <el-select v-model="form.type" style="width: 40%" filterable placeholder="请选择类型">
              <el-option label="教材" value="教材" />
              <el-option label="口袋书" value="口袋书" />
              <el-option label="练习册" value="练习册" />
              <el-option label="考题集" value="考题集" />
              <el-option label="电子资料" value="电子资料" />
            </el-select>
          </el-form-item>
          <el-form-item label="适用地区" prop="province">
            <el-select
              v-model="form.province"
              remote
              filterable
              placeholder="请选择地区"
              :remote-method="remoteMethod" 
              :loading="selectload"
              style="width: 40%"
              @change="selectRegion"
            >
              <el-option v-for="(item, index) in cityList" :key="index" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="资料科目" prop="subject">
            <el-select v-model="form.subject" filterable placeholder="请选择科目" style="width: 40%">
              <el-option v-for="(item, index) in subjectList" :key="index" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item label="资料封面" prop="cover">
            <el-upload
              :headers="headers"
              class="avatar-uploader"
              :action="host + '/api/v1/public/uploadFile'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
<!--              <img v-if="form.cover" :src="getMediaUrl(form.cover)" class="avatar">-->
              <img v-if="form.cover" :src="form.cover" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="详情轮播" prop="lbt_url">
            <el-row :gutter="10" style="margin-left: 0">
              <el-col v-for="(item, index) in form.lbt_url" :key="index" style="margin-bottom: 10px" :span="6">
                <Pictures
                  :url="item"
                  :index="index"
                  @deletefile="(file) => handleRemoveLbtUrl(file, 'lbt_url')"
                />
              </el-col>
              <el-col :span="6" style="padding-left: 0">
                <el-upload
                  :headers="headers"
                  class="avatar-uploader"
                  :action="host + '/api/v1/public/uploadFile'"
                  :show-file-list="false"
                  :on-success="(res) => handleAvatarLbtUrl(res, 'lbt_url')"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus avatar-uploader-icon" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="资料状态" prop="status">
            <el-switch
              v-model="form.status"
              :active-value="1"
              :inactive-value="-1"
              active-text="上架"
              inactive-text="下架"
            />
          </el-form-item>
          <el-form-item label="资料数量" prop="sum">
            <el-input-number v-model="form.sum" controls-position="right" placeholder="请输入/册" style="width: 40%" />
          </el-form-item>
          <el-form-item label="资料价格" prop="price">
            <el-input-number v-model="form.price" controls-position="right" placeholder="请输入价格" style="width: 40%" />
          </el-form-item>
          <el-form-item label="资料分类" prop="category">
            <el-select v-model="form.category" filterable placeholder="请选择分类" style="width: 40%">
              <el-option label="文科" value="文科" />
              <el-option label="理科" value="理科" />
              <el-option label="公共课" value="公共课" />
            </el-select>
          </el-form-item>
          <el-form-item label="资料简介" prop="introduction">
            <el-row :gutter="3" style="margin-left: 0">
              <el-col v-for="(item, index) in form.introduction" :key="index" style="margin-bottom: 10px" :span="6">
                <Pictures
                  :url="item"
                  :index="index"
                  @deletefile="(file) => handleRemoveLbtUrl(file, 'introduction')"
                />
              </el-col>
              <el-col :span="6">
                <el-upload
                  :headers="headers"
                  class="avatar-uploader"
                  :action="host + '/api/v1/public/uploadFile'"
                  :show-file-list="false"
                  :on-success="(res) => handleAvatarLbtUrl(res, 'introduction')"
                  :before-upload="beforeAvatarUpload"
                >
                  <i class="el-icon-plus avatar-uploader-icon" />
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
                </el-upload>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="资料邮费" prop="postage">
            <el-input-number v-model="form.postage" controls-position="right" placeholder="请输入邮费" style="width: 40%" />
          </el-form-item>
        </el-form>
        <div style="width: 40%;display: flex;justify-content: end">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-card>
    </template>
  </BasicLayout>
</template>
<script>
import {
  getSubject,
  getCity,
  addMaterial,
  getMaterialDetails,
  editMaterial
} from '@/api/admin/sys-course'
import { getToken } from '@/utils/auth'
import Pictures from '@/components/Pictures'
export default {
  name: 'NetworkCourse',
  components: {
    Pictures
  },
  data() {
    return {
      headers: { Authorization: 'Bearer ' + getToken() },
      host: '',
      cityList: [],
      subjectList: [],
      form: {
        cover: null,
        status: -1,
        subject: null,
        lbt_url: [],
        introduction: []
      },
      rules: {
        name: [
          { required: true, message: '资料名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '资料类型不能为空', trigger: 'blur' }
        ],
        subject: [
          { required: true, message: '资料科目不能为空', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '选择适用地区', trigger: 'blur' }
        ],
        cover: [
          { required: true, message: '资料封面不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '资料状态不能为空', trigger: 'blur' }
        ],
        sum: [{ required: true, message: '资料数量不能为空', trigger: 'blur' }],
        price: [
          { required: true, message: '资料价格不能为空', trigger: 'blur' }
        ],
        introduction: [
          { required: true, message: '资料简介不能为空', trigger: 'blur' }
        ],
        postage: [
          { required: true, message: '资料邮费不能为空', trigger: 'blur' }
        ],
        lbt_url: [{ required: true, message: '上传详情轮播', trigger: 'blur' }]
      },
      selectload: false
    }
  },
  watch: {
    form: {
      deep: true,
      handler(val) {
        if (val.province) {
          getSubject({ province: val.province }).then(res => {
            this.subjectList = res?.data || []
          })
        }
      }
    }
  },
  created() {
    this.host = process.env.VUE_APP_BASE_API
    getCity().then(res => {
      this.cityList = res?.data || []
    })
    if (this.$route.params.id) {
      /** 获取课程详情 */
      const id = this.$route.params && Number(this.$route.params.id)
      getMaterialDetails(id).then(response => {
        const { data = {}} = response
        this.form = {
          ...data,
          price: data.price / 100,
          postage: data.postage / 100,
          lbt_url: data?.lbt_url?.length > 0 ? data?.lbt_url.split(',') : [],
          introduction: data?.introduction?.includes('://')
            ? data?.introduction.split(',')
            : []
        }
      })
    }
  },
  methods: {
    cancel() {
      this.$router.push('/admin/sys-course/information')
    },
    selectRegion(val) {
      this.form.subject = null
      getSubject({ province: val }).then(res => {
        this.subjectList = res?.data || []
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.$route.params.id) {
            editMaterial({
              ...this.form,
              price: this.form.price * 100,
              postage: this.form.postage * 100,
              lbt_url: this.form.lbt_url.toString(),
              introduction: this.form.introduction.toString()
            }).then(res => {
              if (res.code === 200) {
                this.msgSuccess(res.msg)
                this.$router.push('/admin/sys-course/information')
              } else {
                this.msgError(res.msg)
              }
            })
            return
          }
          addMaterial({
            ...this.form,
            price: this.form.price * 100,
            postage: this.form.postage * 100,
            lbt_url: this.form.lbt_url.toString(),
            introduction: this.form.introduction.toString()
          }).then(res => {
            if (res.code === 200) {
              this.msgSuccess(res.msg)
              this.$router.push('/admin/sys-course/information')
            } else {
              this.msgError(res.msg)
            }
          })
        }
      })
    },
    handleRemoveLbtUrl(file, type) {
      if (type === 'introduction') {
        this.form.introduction = this.form.introduction.filter(
          (item, index) => file !== index
        )
      } else {
        this.form.lbt_url = this.form.lbt_url.filter(
          (item, index) => file !== index
        )
      }
    },
    handleAvatarSuccess(res) {
      this.form.cover = res.data.full_path
    },
    handleAvatarLbtUrl(res, type) {
      if (type === 'introduction') {
        this.form.introduction.push(res.data.full_path)
      } else {
        this.form.lbt_url.push(res.data.full_path)
      }
    },
    beforeAvatarUpload(file) {
      const isLt05M = file.size / 1024 / 1024 < 5
      const isJPG = file.type.indexOf('image/') === -1
      if (isJPG) {
        this.$message.error(
          '文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件'
        )
      }
      if (!isLt05M) {
        this.$message.error('上传头像图片大小不能超过 2M!')
      }
      return !isJPG && isLt05M
    },
    remoteMethod(query) {
      if (query !== '') {
        this.selectload = true
        getCity({ name: query }).then(res => {
          this.cityList = res?.data || []
          this.selectload = false
        })
      } else {
        this.cityList = []
      }
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.addsonchapter {
  border: 1px solid #c0c4cc;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  color: #3d64d4;
}
</style>
